package com.example.day14_gifloadofc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

@SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity {

    private GifHandler gifHandler;
    private ImageView iv_showgif;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(this);
        iv_showgif = findViewById(R.id.iv_showgif);
    }

    //region 检查存储权限
    public   void verifyStoragePermissions(Activity activity) {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.WRITE_EXTERNAL_STORAGE" };
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //endregion

    //region handler
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg)
        {
            int delay = gifHandler.updateFrame(bitmap);
            handler.sendEmptyMessageDelayed(1,delay);
            iv_showgif.setImageBitmap(bitmap);
        }
    };
    //endregion

    public void ndkLoadGif(View view)
    {
        File file = new File(Environment.getExternalStorageDirectory(), "demo.gif");
        Log.e("file is exist",""+file.exists());
        gifHandler = GifHandler.load(file.getAbsolutePath());
        int width = gifHandler.getWidth();
        int height = gifHandler.getHeight();
        Log.e("ndkLoadGif","宽："+width+"  高："+height);
        bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        int delay = gifHandler.updateFrame(bitmap);
        iv_showgif.setImageBitmap(bitmap);
        handler.sendEmptyMessageDelayed(1,delay);
    }

}
